<?php

namespace app\adminapi\controller\v1\system;

use think\App;
use think\Request;
use app\common\model\user\UserGroup;
use app\common\controller\AdminController;


/**
 * 菜单管理
 * @package app\adminapi\controller\v1\setting
 * User: liuhongbin
 * Date: 2021-05-15 19:54
 */
class Menu extends AdminController
{
    /**
     * @var \app\common\model\system\Menu
     */
    public $MenuModel;

    public function __construct(App $app)
    {
        $this->MenuModel = new \app\common\model\system\Menu();
        parent::__construct($app);
    }

    /**
     * 显示资源列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOption()
    {
        $data = [];
        $list = $this->MenuModel->where([])->order("sort asc")->select()->toArray();
        foreach ($list as $value) {
            $option = array(
                "label"     => $value['menu_name'],
                "pid"       => $value["pid"],
                "value"     => $value["id"],
                "id"        => $value['id'],
                'menu_type' => $value['menu_type'],
                'is_show'   => $value['is_show']
            );
            $data[$value['id']] = $option;
        }
        return $this->success('ok', get_tree_children($data));
    }

    public function getList()
    {
        $list = $this->MenuModel->where([])->order("sort asc")->select()->toArray();
        return $this->success('', get_tree_children($list));
    }


    public function getMenus()
    {
        $UserGroupModel = new UserGroup();
        $group_id = $this->userInfo['group_id'];
        $user_group = $UserGroupModel->where(['id' => $group_id])->find();
        if ($user_group) {

            $where = [['menu_type', '=', 1], ['is_show', '=', 1]];
            if (!$this->auth->isFounder()) {
                $where[] = ['id', 'in', (array)$user_group['rules']];
            }
            $list = $this->MenuModel->where($where)->order("sort asc")->cache(true)->select()->toArray();
            foreach ($list as $value) {
                $option = array(
                    "pid"       => $value["pid"],
                    "value"     => $value["id"],
                    "id"        => $value['id'],
                    "path"      => $value['menu_path'],
                    "meta"      => [
                        "icon"  => $value['icon'],
                        "title" => $value['menu_name']
                    ],
                    'menu_type' => $value['menu_type']
                );
                $data[$value['id']] = $option;
            }
        } else {
            $data = [];
        }
        return $this->success('ok', get_tree_children($data));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $formData = $request->post("formData");
        if ($formData['menu_type'] == 1) {
            if (!$formData['menu_name'] || !$formData['menu_path']) {
                return $this->error("菜单名称或者路由地址不能为空");
            }

            if (!$formData['auth_mark']) {
                return $this->error("权限标识不能为空");
            }
        } else {
            if (!$formData['menu_name'] || !$formData['api_url']) {
                return $this->error("接口名称或者接口地址不能为空");
            }
            if (!$formData['methods']) {
                return $this->error("请求方式不能为空");
            }
        }
        $this->MenuModel->save($formData);
        return $this->success("新增成功");
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        if (!$id) {
            return $this->error("菜单不存在");
        }
        $data = $this->MenuModel->where(['id' => $id])->find();
        if (!$data) {
            return $this->error("菜单不存在");
        }
        return $this->success("ok", $data);
    }

//这里有bug
//    private function getMenuOptions()
//    {
//        $list = $this->MenuModel->where([])->order("sort desc")->select()->toArray();
//        foreach ($list as $value) {
//            $option = array(
//                "label"     => $value['menu_name'],
//                "pid"       => $value["pid"],
//                "value"     => $value["id"],
//                "id"        => $value['id'],
//                'menu_type' => $value['menu_type'],
//                'is_show'   => $value['is_show']
//            );
//            $data[$value['id']] = $option;
//        }
//        return get_tree_children($data);
//    }
//
//    public function getForm($id)
//    {
//        $rule = array();
//        $menuOptions = $this->getMenuOptions();
//        $res = $this->MenuModel->where(['id' => $id])->findOrEmpty();
//        //创建表单
//        $form = Form::createForm("/adminapi/system/menu/save?id=" . $id)->setMethod("post");
//        $col = Form::col()->lg(12)->md(24)->xs(24);
//        //新增表单
//        $rule[] = Form::radio("menu_type", "规则类型", $res['menu_type'] ?? '1')->size('small')
//            ->options([
//                    ['label' => '菜单', 'value' => 1],
//                    ['label' => '接口', 'value' => 2],
//                ]
//            )->appendControl(1, [
//                Form::dkInput('menu_name', '菜单名称', $res['menu_name'] ?? '')->required()->col($col),
//                Form::cascader('pid', "父级分类", $res['pid']?? [])->options($menuOptions)
//                    ->clearable(true)->filterable(true)
//                    ->props([['checkStrictly' => true], ['emitPath' => false]])->col($col),
//
//                Form::dkInput('menu_path', '路由地址', $res['menu_path'] ?? '')->required()->col($col),
//                Form::dkInput('auth_mark', '权限标识', $res['auth_mark'] ?? '')->required()->col($col),
//                Form::DkIconInput('icon', '图标', $res['icon'] ?? '')->col($col),
//                Form::dkInputNumber('sort', '排序', $res['sort'] ?? '')->col($col),
//
//                Form::radio('is_show', '状态', $res['is_show'] ?? 0)->options([
//                    ['label' => '显示', 'value' => 1],
//                    ['label' => '隐藏', 'value' => 0]
//                ])->col($col),
//                Form::radio('is_show_path', '是否为隐藏菜单', $res['is_show_path'] ?? 0)->options([
//                    ['label' => '是', 'value' => 1],
//                    ['label' => '否', 'value' => 0]
//                ])->col($col),
//
//
//            ])->appendControl(2, [
//                Form::dkInput('menu_name', '接口名称', $res['menu_name'] ?? '')->required()->col($col),
//                Form::cascader('pid', "父级分类", [$res['pid']] ?? [])->options($menuOptions)
//                    ->clearable(true)->filterable(true)
//                    ->props(['checkStrictly' => true, 'emitPath' => false])->col($col),
//                Form::dkInput('api_url', '接口地址', $res['api_url'] ?? '')->required()->col($col),
//                Form::select('methods', '请求方式', $res['methods'] ?? '')->options([
//                    ['value' => '', 'label' => '请求'],
//                    ['value' => 'GET', 'label' => 'GET'],
//                    ['value' => 'POST', 'label' => 'POST'],
//                    ['value' => 'PUT', 'label' => 'PUT'],
//                    ['value' => 'DELETE', 'label' => 'DELETE'],
//                ])->required()->col($col),
//                Form::dkInputNumber('sort', '排序', $res['sort'] ?? '')->col($col),
//            ])->required();
//        $form->setTitle($res['id'] ? "编辑菜单" : "新增菜单")->setRule($rule);
//        return $this->success("", Form::getFormData($form));
//    }


    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //

    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        if (!$id) {
            return $this->error("菜单不存在");
        }
        $data = $this->MenuModel->where(['id' => $id])->find();
        if (!$data) {
            return $this->error("菜单不存在");
        }
        $formData = $request->post('formData');
        if ($formData['id'] === $formData['pid']) {
            return $this->error("父级分类不得选择自己");
        }
        $data->save($formData);
        return $this->success("修改成功");
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $children = $this->MenuModel->where(['pid' => $id])->find();
        if (!$children) {
            $menu = $this->MenuModel->where(['id' => $id])->find();
            if (!$menu) {
                return $this->success("删除失败，菜单不存在");
            }
            $this->MenuModel->where(['id' => $id])->delete();
            return $this->success("删除成功");
        } else {
            return $this->error("请先删除子节点菜单");
        }
    }
}
